import createVoroPP from './cluster-module.js';
const mod = await createVoroPP();

const rand = Math.random;
const log = true;

const distance = 0.3;

const points = [];

function genPoints(nPoints) {
    points.length = 0;
    for (let i = 0; i < nPoints; ++i) {
        const x = rand();
        const y = rand();
        points.push([x, y]);
    }
}

genPoints(10000);

const t0 = performance.now();

const szInput = 1 + points.length * 3; // Particles

const pInput = mod._malloc(szInput * 8);
const input = new Float64Array(mod.HEAPU8.buffer, pInput, szInput);
let ip = 0;

input[ip++] = points.length;
for (let i = 0; i < points.length; ++i) {
    input[ip++] = i;
    input[ip++] = points[i][0];
    input[ip++] = points[i][1];
}

let strOutput = '';

const pRes = mod._calculate_cluster(pInput, distance);
const dummyArr = new Float64Array(mod.HEAPU8.buffer, pRes, 1);
const resSize = dummyArr[0];
const resArr = new Float64Array(mod.HEAPU8.buffer, pRes, resSize);
let nCells = resArr[1];
let pos = 2;
var clusterData = [];
for (let cix = 0; cix < nCells; ++cix) {
    const id = resArr[pos++];
    const px = resArr[pos++];
    const py = resArr[pos++];
    const count = resArr[pos++];
    const parentId = resArr[pos++];
    var obj = {
        id,
        px,
        py,
        count,
        parentId,
    };
    clusterData[id - 1] = obj;

    if (parentId > 0) {
        if (typeof clusterData[parentId - 1] == 'undefined') clusterData[parentId - 1] = {};
        if (typeof clusterData[parentId - 1].clusters == 'undefined')
            clusterData[parentId - 1].clusters = [];
        clusterData[parentId - 1].clusters.push(obj);
    } else {
        clusterData[id - 1].clusters = [];
        console.log(
            `ID: ${id} (${px.toFixed(2)}, ${py.toFixed(2)}), count ${count.toFixed(
                0
            )}, parentId ${parentId.toFixed(0)}`
        );
    }
}

mod._free(pRes);
mod._free(pInput);

const t1 = performance.now();

console.log(
    `Calculated result for ${points.length} particles, giving ${nCells} Voronoi cells: ${
        t1 - t0
    } msec`
);

// console.log(strOutput);
